package org.hospital.service.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hospital.entity.Client;
import org.hospital.entity.ClientDAO;
import org.hospital.entity.Clinic;
import org.hospital.entity.ClinicDAO;
import org.hospital.entity.Department;
import org.hospital.entity.DepartmentDAO;
import org.hospital.entity.Employee;
import org.hospital.entity.EmployeeDAO;
import org.hospital.entity.MedicalCard;
import org.hospital.entity.MedicalCardDAO;
import org.hospital.entity.MedicalRecord;
import org.hospital.entity.MedicalRecordDAO;
import org.hospital.entity.Project;
import org.hospital.entity.ProjectDAO;
import org.hospital.entity.TreatInfo;
import org.hospital.entity.TreatInfoDAO;
import org.hospital.service.MedicalCardService;
import org.hospital.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Service
public class MedicalCardServiceImpl implements MedicalCardService {

	@Autowired
	private MedicalCardDAO mcDao;
	@Autowired
	private MedicalRecordDAO mrDao;
	@Autowired
	private EmployeeDAO eDao;
	@Autowired
	private TreatInfoDAO tiDao;
	@Autowired
	private ProjectDAO pjDao;
	@Autowired
	private ClinicDAO cDao;
	@Autowired
	private ClientDAO clientDao;
	@Autowired
	private DepartmentDAO dpmDao;

	@Override
	public MedicalCard getById(int id) {
		return mcDao.findById(id);
	}

	@Override
	public MedicalCard addEntity(MedicalCard entity) {
		return mcDao.merge(entity);
	}

	@Override
	public MedicalCard saveEntity(MedicalCard entity) {
		return mcDao.merge(entity);
	}

	@Override
	public List<MedicalCard> addEntityList(List<MedicalCard> mcList) {
		List<MedicalCard> result = new ArrayList<MedicalCard>();

		for (int i = 0; i < mcList.size(); i++) {
			MedicalCard mc = mcList.get(i);
			result.add(mcDao.merge(mc));
		}

		return result;
	}
	
	@Override
	public TreatInfo createTreatInfo(int projectId, int clientId, int excutorId) {
		
		//获取所有符合的治疗卡信息按id排序
		List<MedicalCard> mcList = mcDao.getByProjectAndClient(projectId, clientId);
		MedicalCard aimMC = null; // 最终目标治疗卡上的未过期最早的信息
		for (int i = 0; i < mcList.size(); i++) {
			MedicalCard mc = mcList.get(i);
			if (mc.getDeadline().before(new Timestamp(DateUtil.getNowLong()))) {
				mc.setStatus(-2);
				mcDao.merge(mc);
				continue;
			}
			aimMC = mc;
			break;
		}

		// 不存在未过期的治疗卡项目
		if (aimMC == null) {
			return null;
		}
		//扣除剩余次数
		int restNumber = aimMC.getRestNumber() - 1;
		aimMC.setRestNumber(restNumber);
		if(restNumber == 0) {
			aimMC.setStatus(-1);
		}
		mcDao.merge(aimMC);
		

		Employee excutor = eDao.findById(excutorId);
		TreatInfo ti = new TreatInfo();
		ti.setClientId(clientId);
		ti.setExcutorId(excutorId);
		ti.setMedicalCardId(aimMC.getMedicalCardId());
		ti.setDepartmentId(excutor.getDepartmentId());
		ti.setClinicId(excutor.getClinicId());
		ti.setUnitPrice(aimMC.getUnitPrice());
		ti.setClinicCost(aimMC.getClinicCost());
		ti.setExcutorCost(aimMC.getExcutorCost());
		ti.setTreatTime(new Timestamp(DateUtil.getNowLong()));
		
		ti = tiDao.merge(ti);
		
		return ti;
	}

	@Override
	public JSONArray getMedicalCardInfo(int clientId) {
		
		JSONArray resultJA = new JSONArray();
		Timestamp now = new Timestamp(DateUtil.getNowLong());//当前时间
		//获取client所有project信息
		Client client = clientDao.findById(clientId);
		List<Project> pjList = pjDao.getClientProject(clientId);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		for(int i = 0;i < pjList.size();i++) {
			Project pj = pjList.get(i);
			//获取client+projectId所有MedicalCard信息
			List<MedicalCard> mcList = mcDao.getByProjectAndClient(pj.getProjectId(), clientId);
			JSONObject resultJO = new JSONObject();
			int restNumber = 0; //剩余次数
			int totalNumber = 0; //总次数
			String startTime = "0"; //开始时间
			String deadline = "0";  //过期时间
			
			//TODO  项目过期时间应该取最早的还是最晚的
			for (int j = 0; j < mcList.size(); j++) {
				MedicalCard mc = mcList.get(j);
				if(mc.getDeadline().before(now)){
					mc.setStatus(-2);
					mcDao.merge(mc);
					continue;
				}
				restNumber += mc.getRestNumber();
				totalNumber += mc.getTotalNumber();
				
				if(j<=mcList.size()-2){
					if(mc.getStartTime().before(mcList.get(j+1).getStartTime())){
						startTime=sdf.format(mc.getStartTime());
					}else{
						startTime=sdf.format(mcList.get(j+1).getStartTime());
					}
					if(mc.getDeadline().before(mcList.get(j+1).getDeadline())){
						deadline=sdf.format(mcList.get(j+1).getDeadline());
					}else{
						deadline=sdf.format(mc.getDeadline());
					}
				}else{
					startTime=sdf.format(mc.getStartTime());
					deadline=sdf.format(mc.getDeadline());
				}
			}
			
			if(restNumber == 0) {	//如果治疗卡记录均是过期的则
				continue;
			}
			
			resultJO.put("clientName", client.getName());
			resultJO.put("clientId", client.getClientId());
			resultJO.put("unitPrice", pj.getUnitPrice());
			resultJO.put("projectId", pj.getProjectId());
			resultJO.put("projectName", pj.getName());
			resultJO.put("restNumber", restNumber);
			resultJO.put("totalNumber", totalNumber);
			resultJO.put("startTime", startTime);
			resultJO.put("deadline", deadline);
			resultJA.add(resultJO);
		}
		return resultJA;
	}

	@Override
	public JSONArray getClientTreatInfo(int clientId) {
		JSONArray resultJA = new JSONArray();
		//获取客户所有治疗信息
		List<TreatInfo> tiList = tiDao.findByClientId(clientId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//格式化数据
		for (int i = 0; i < tiList.size(); i++) {
			TreatInfo ti = tiList.get(i);
			JSONObject resultJO = new JSONObject();
			
			Clinic clinic = cDao.findById(ti.getClinicId());
			Department dpm = dpmDao.findById(ti.getDepartmentId());
			Employee excutor = eDao.findById(ti.getExcutorId());
			MedicalCard mc = mcDao.findById(ti.getMedicalCardId());
			Project project = pjDao.findById(mc.getProjectId());
			Client client = clientDao.findById(ti.getClientId());
			
			resultJO.put("excutorId", excutor.getEmployeeId());
			resultJO.put("excutorName", excutor.getName());
			resultJO.put("excutorCode", excutor.getEmployeeCode());
			resultJO.put("projectName", project.getName());
			resultJO.put("unitPrice", ti.getUnitPrice());
			resultJO.put("clientName", client.getName());
			resultJO.put("clinicId", clinic.getClinicId());
			resultJO.put("clinicName", clinic.getName());
			resultJO.put("departmentId", dpm.getDepartmentId());
			resultJO.put("departmentName", dpm.getName());
			resultJO.put("treatTime", sdf.format(ti.getTreatTime()));
			resultJO.put("totalNumber", mc.getTotalNumber());
			resultJO.put("restNumber", mc.getRestNumber());
			resultJO.put("startTime", sdf.format(mc.getStartTime()));
			resultJO.put("deadline", sdf.format(mc.getDeadline()));
			resultJA.add(resultJO);
		}
		
		return resultJA;
	}

	@Override
	public MedicalRecord creatrMedicalRecord(MedicalRecord mr) {
		return mrDao.merge(mr);
	}

	@Override
	public JSONArray getClientMedicalRecord(int clientId) {
		JSONArray resultJA = new JSONArray();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Client client = clientDao.findById(clientId);
		List<MedicalRecord> mrList = mrDao.findByClientId(clientId);
		
		//格式化数据
		Clinic clinic;
		Department dpm;
		Employee doctor;
		for (int i = 0; i < mrList.size(); i++) {
			MedicalRecord mr = mrList.get(i);
			JSONObject resultJO = new JSONObject();
			clinic = cDao.findById(mr.getClinicId());
			dpm = dpmDao.findById(mr.getDepartmentId());
			doctor = eDao.findById(mr.getEmployeeId());
			
			resultJO.put("clientName", client.getName());
			resultJO.put("medicalRecordId",mr.getMedicalRecordId());
			resultJO.put("clinicName", clinic.getName());
			resultJO.put("departmentName", dpm.getName());
			resultJO.put("doctorName", doctor.getName());
			resultJO.put("doctorCode", doctor.getEmployeeCode());
			resultJO.put("treatTime", sdf.format(mr.getDatetime()));
			resultJO.put("diseaseName", mr.getDiseaseName());
			resultJA.add(resultJO);
		}
		
		return resultJA;
	}

}
